package cn.jofei.common.monitor;

import cn.jofei.common.monitor.interf.Monitor;
import cn.jofei.common.monitor.msg.DingMsg;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 端口监听
 *
 * @author Jofei Bao
 * @version ngbao v2.0
 * @date 2022年10月25日 18:40
 */
public class ServerPortMonitor extends Monitor {
    /**
     * IP
     */
    private String host;
    /**
     * 端口
     */
    private Integer port;

    /**
     * @param monitName 监控服务名称
     * @param host      IP
     * @param port      端口
     */
    public ServerPortMonitor(String monitName, String host, Integer port) {
        super.monitName = monitName;
        this.host = host;
        this.port = port;
    }

    @Override
    public DingMsg getMsg() {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), 3000);
            if (!isOk()) {
                setOk(true);
                return DingMsg.markdown("监控信息")
                        .text("#### " + monitName + "正常\n" +
                                "###### 恢复时间：" + TIME_FORMATTER.format(LocalDateTime.now().atOffset(ZoneOffset.UTC)) + "\n")
                        .build();
            }
            return null;
        } catch (Exception e) {
            setOk(false);
            return DingMsg.markdown("监控信息")
                    .text("#### " + monitName + "异常\n" +
                            "###### 报警时间：" + TIME_FORMATTER.format(LocalDateTime.now().atOffset(ZoneOffset.UTC)) + "\n" +
                            "##### 友情连接 [服务器列表]() \n").build();
        }
    }
}
